package com.shenhan.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.IntStream;

/**
 * @author shenhan
 * @create 2020/6/10 17:25
 * @description
 */
public class SetTest {
    /**
     * hashSet不安全解决方案：
     * 1、Collections.synchronizedSet(new HashSet<>())
     * 2、new CopyOnWriteArraySet<>()
     * @param args
     */
    public static void main(String[] args) {
        // HashSet本质就是HashMap
//        Set<String> hashSet = new HashSet<>();
//        Set<String> hashSet = Collections.synchronizedSet(new HashSet<>());
        Set<String> hashSet = new CopyOnWriteArraySet<>();
        IntStream.range(1, 30).forEach(i -> new Thread(() -> {
            hashSet.add(UUID.randomUUID().toString().substring(0, 5));
            System.out.println(hashSet);
        }, String.valueOf(i)).start());
    }
}
